#!/usr/bin/python
# This script parses gene names from KEGG website given a list of KO numbers
# Usage: python genenameFromKEGG.py ko.list
# ko.list contains locus tag and KO numbers separated by tabs. Example:
#GLBK_0001	K02313
#GLBK_0002	K06980
#GLBK_0003	K03980
#GLBK_0004
#GLBK_0005
#GLBK_0006
#GLBK_0007
#GLBK_0008
#GLBK_0009	K03676
#GLBK_0010	K01920

import sys
import re
from SOAPpy import WSDL

wsdl = 'http://soap.genome.jp/KEGG.wsdl'
serv = WSDL.Proxy(wsdl)

klistfile = sys.argv[1]

klf = open(klistfile, "rU")
kl = klf.readlines()

pattern = re.compile('.*NAME        (.*)\n(DEFINITION|CLASS|PATHWAY|MODULE|OTHER|GENES).*')
keggo = re.compile('K0.*')
genecase = re.compile('[a-z][a-z][a-z][A-Z0-9+]|[a-z][a-z][a-z]')

for line in kl:
    l = line.split('\t')
    if len(l) > 1:
        locustag = l[0]
        ko = l[1].strip()
        q = "orthology:" + ko
        f = serv.bget(q)

        if pattern.search(f):
            m = pattern.search(f)
            gl = m.group(1).split(',')
            if len(gl) > 1:
                genelist = []
                for i in gl:
                    s = i.strip()
                    if not genecase.match(s):
                        pass
                    else:
                        genelist.append(s)
                if len(genelist) < 1:
                    print locustag + "\t" + ko + "\t" + "-"
                else:
                    print locustag + "\t" + ko + "\t" + genelist[0]
            else:
                gene = m.group(1)
                if genecase.match(gene):
                    print locustag + "\t" + ko + "\t" + gene
                else:
                    print locustag + "\t" + ko + "\t" + "-"
        else:
            print locustag + "\t" + ko + "\t" + "-"
    else:
        locustag = l[0].strip()
        print locustag + "\t" + "-" + "\t" + "-"

klf.close()
